<template>
  <div class="chat-layout" :class="{ 'with-medical': store.showMedicalPanel }">
    <!-- 左侧：模型选择（上半部分）和会话历史（下半部分） -->
    <div class="left-column">
      <!-- 上半部分：模型选择 -->
      <div class="left-section model-selector">
        <ModelSelector />
      </div>
      
      <!-- 下半部分：会话历史 -->
      <div class="left-section chat-history">
        <ChatHistory />
      </div>
    </div>

    <!-- 中间：聊天 -->
    <div class="middle-column">
      <!-- 普通聊天模式 -->
      <div v-if="!store.showMedicalPanel" class="normal-chat">
        <div class="chat" ref="chatRef">
          <div class="chat-content" ref="contentRef">
            <!-- 消息项 - 使用flex布局更便于控制顺序 -->
            <div
              v-for="(m, i) in store.messages"
              :key="i"
              :class="['msg', m.role === 'user' ? 'user' : 'assistant']"
            >
              <!-- AI消息：头像在左，气泡在右 -->
              <div v-if="m.role !== 'user'" class="avatar" aria-hidden="true">
                <span>AI</span>
              </div>
              
              <div class="bubble">
                <MarkdownRenderer :content="m.content" />
              </div>
              
              <!-- 用户消息：头像在右，气泡在左（放在气泡后面实现右对齐） -->
              <div v-if="m.role === 'user'" class="avatar" aria-hidden="true">
                <span>你</span>
              </div>
            </div>

            <div ref="endRef" class="scroll-anchor"></div>
          </div>
        </div>

        <div class="input-bar">
          <textarea
            v-model="input"
            :placeholder="placeholder"
            :disabled="store.streaming"
            @keydown.enter.exact.prevent="send"
          />
          <button class="btn primary" :disabled="!input.trim() || store.streaming" @click="send">发送</button>
          <button class="btn ghost" :disabled="!store.streaming" @click="abort">中断</button>
        </div>
      </div>

      <!-- 医疗对话模式 -->
      <div v-else class="medical-chat">
        <div class="medical-chat-header">
          <h3>🔍 Med-DistillFL影像分析工作台</h3>
        </div>
        
        <!-- 主内容区 -->
        <div class="medical-content">
          <!-- 输入侧边栏 -->
          <div class="input-sidebar">
            <div class="image-upload-section">
              <h4>📷 上传医学影像</h4>
              <div class="upload-area" :class="{ 'drag-over': dragOver }" 
                   @drop="handleDrop" 
                   @dragover.prevent="dragOver = true"
                   @dragleave="dragOver = false"
                   @click="triggerFileInput">
                <input ref="fileInput" type="file" accept="image/*" @change="handleFileSelect" style="display: none;">
                <div v-if="!selectedImage" class="upload-placeholder">
                  <div class="upload-icon">📁</div>
                  <p>点击或拖拽上传医学影像</p>
                  <p class="upload-hint">支持 JPG, PNG, DICOM 等格式</p>
                </div>
                <div v-else class="image-preview">
                  <img :src="imagePreviewUrl" alt="医学影像预览">
                  <button class="remove-image" @click.stop="removeImage">✕</button>
                </div>
              </div>
            </div>
            
            <!-- 高级参数设置 -->
            <div class="advanced-params">
              <h5>高级参数设置</h5>
              <div class="param-row">
                <label>生成温度: {{ temperature }}</label>
                <input type="range" v-model="temperature" min="0" max="1" step="0.1" class="slider">
              </div>
              <div class="param-row">
                <label>Top P 参数: {{ topP }}</label>
                <input type="range" v-model="topP" min="0" max="1" step="0.1" class="slider">
              </div>
            </div>
            
            <!-- 分析指令输入 -->
            <div class="analysis-input">
              <label>分析指令</label>
              <textarea v-model="inputText" rows="3" 
                        placeholder="请输入您的问题..."></textarea>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons">
              <button class="btn primary analyze-btn" 
                      @click="startAnalysis" 
                      :disabled="!selectedImage || analyzing">
                {{ analyzing ? '分析中...' : '开始分析' }}
              </button>
              <button class="btn secondary" @click="clearInput">清空输入</button>
            </div>
          </div>

          <!-- 聊天主界面 -->
          <div class="chat-main">
            <div class="chatbot-container" ref="medicalChatContainer">
              <div v-if="chatHistory.length === 0" class="no-messages">
                <p>请上传医学影像并开始分析</p>
              </div>
              <div v-else class="chat-messages">
                <div v-for="(message, index) in chatHistory" :key="index" class="message-item">
                  <div class="message-header">
                    <span class="message-role">{{ message.role }}</span>
                    <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                  </div>
                  <div class="message-content" v-html="renderMarkdown(message.content)"></div>
                </div>
              </div>
              <div v-if="analyzing" class="analyzing-indicator">
                <div class="spinner"></div>
                <span>AI正在分析医学影像，请稍候...</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 报告生成区 -->
        <div class="report-section">
          <div class="report-actions">
            <button class="btn primary" @click="generateReport" :disabled="!chatHistory.length || generatingReport">
              {{ generatingReport ? '生成中...' : '生成诊疗报告' }}
            </button>
            <button class="btn secondary" @click="downloadReport" :disabled="!medicalReport">
              下载报告
            </button>
          </div>
          <div v-if="medicalReport" class="report-content">
            <div class="markdown-content" v-html="renderMarkdown(medicalReport)"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧：医疗影像分析面板 -->
    <div v-if="store.showMedicalPanel" class="right-column">
      <MedicalPanel />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import {useChatStore} from '@/stores/chat';
import { API_BASE_URL, MODELS } from '@/config/api';
import MarkdownRenderer from '@/components/MarkdownRenderer.vue';
import ModelSelector from '@/components/ModelSelector.vue';
import ChatHistory from '@/components/ChatHistory.vue';
import MedicalPanel from '@/components/MedicalPanel.vue';

const store = useChatStore();
const chatRef = ref<HTMLElement | null>(null);
const contentRef = ref<HTMLElement | null>(null); // 内容容器
const endRef  = ref<HTMLElement | null>(null);   // 锚点

const input = ref('');
const placeholder = '请输入内容，Enter 发送。';

let controller: AbortController | null = null;

// 医疗对话模式的数据
const selectedImage = ref<File | null>(null);
const imagePreviewUrl = ref<string>('');
const inputText = ref('');
const dragOver = ref(false);
const fileInput = ref<HTMLInputElement | null>(null);

// 分析相关状态
const analyzing = ref(false);
const generatingReport = ref(false);

// 高级参数
const temperature = ref(0.8);
const topP = ref(0.4);

// 聊天历史和分析结果
const chatHistory = ref<Array<{role: string, content: string, timestamp: string}>>([]);
const medicalReport = ref<string>('');

// 医疗对话模式的滚动控制
const medicalChatContainer = ref<HTMLElement | null>(null);


onMounted(async () => {
  // 刷新后拉取会话列表（不自动选中）
  await store.fetchSessions();
});
async function ensureSessionIfNeeded(seedTitle?: string){
  if (store.currentSessionId) return;
  const id = await store.createSession();        // 不传参
  if (seedTitle) {
    await store.renameSession(id, seedTitle.slice(0, 40)); // 用首条消息做标题
  }
}

async function send(){
  const content = input.value.trim();
  if(!content || store.streaming) return;

  // 没有选中的会话则自动创建
  await ensureSessionIfNeeded(content);
  // 再次确认：如果仍没有会话，直接返回
  if(!store.currentSessionId) return;

  // 置顶当前会话（可选，但体验更好）
  store.touchSession(store.currentSessionId);

  store.appendMessage({ role:'user', content });
  store.appendMessage({ role:'assistant', content: '' });

  input.value = '';
  store.setStreaming(true);
  controller = new AbortController();

  const modelParam = MODELS[store.model].apiParam;

  try{
    const r = await fetch(`${API_BASE_URL}/api/chat/stream?session_id=${store.currentSessionId}&model=${modelParam}`, {
      method: 'POST',
      headers: { 'Content-Type':'application/json' },
      body: JSON.stringify({ messages: store.messages }),
      signal: controller.signal,
    });
    if(!r.ok || !r.body) throw new Error(`HTTP ${r.status}`);
    // 会话有新消息，更新“最近使用时间”并把它顶到列表前面
    store.touchSession(store.currentSessionId);
    const reader = r.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while(true){
      const { value, done } = await reader.read();
      if(done) break;
      buffer += decoder.decode(value, { stream: true });

      const parts = buffer.split('\n\n');
      for(let i=0; i<parts.length-1; i++){
        const chunk = parts[i];
        if(chunk.includes('data: ')){
          const payload = chunk.replace('data: ', '');
          if(payload !== '[DONE]') store.updateLastAssistantDelta(payload);
        }else{
          store.updateLastAssistantDelta(chunk);
        }
      }
      buffer = parts[parts.length-1];
    }
  }catch(err){
    store.updateLastAssistantDelta(`\n\n> 请求中断或失败：${String(err)}`);
  }finally{
    store.setStreaming(false);
    controller = null;
  }
}
function abort(){ if(controller) controller.abort(); }
onBeforeUnmount(() => { if(controller) controller.abort(); });


// 是否“贴底”状态（用户没主动往上滚）
const shouldStick = ref(true);
const SCROLL_TOL = 32; // 距离底部多少像素内视为“贴底”
function isAtBottom(el: HTMLElement){
  return el.scrollHeight - (el.scrollTop + el.clientHeight) <= SCROLL_TOL;
}
function onChatScroll(){
  if (!chatRef.value) return;
  shouldStick.value = isAtBottom(chatRef.value);
}
function autoScroll(force = false){
  const el = chatRef.value;
  if (!el) return;
  if (force || shouldStick.value) {
    // 想要动画可用 behavior: 'smooth'（流式时可能有轻微动画累积）
    el.scrollTo({ top: el.scrollHeight });
  }
}
// 用锚点滚到底；流式时用 behavior:'auto'，避免平滑动画落后
function scrollToEnd(force = false){
  const el = chatRef.value;
  const anchor = endRef.value;
  if (!el || !anchor) return;

  if (force || shouldStick.value) {
    // 双 rAF，等一轮/两轮布局（Markdown/公式/代码块）
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        anchor.scrollIntoView({ block: 'end', behavior: 'auto' });
      });
    });
  }
}
// 移除重复的监听，避免滚动逻辑冲突
watch(() => store.messages.length, async () => {
  await nextTick();
  scrollToEnd(true);
});
// 仅保留一个流式增量的监听，使用 scrollToEnd 方法
watch(
  () => store.messages.length ? store.messages[store.messages.length - 1].content : '',
  async () => {
    await nextTick();
    scrollToEnd(false);
  }
);
onMounted(() => {
  chatRef.value?.addEventListener('scroll', onChatScroll, { passive: true });
});
onBeforeUnmount(() => {
  chatRef.value?.removeEventListener('scroll', onChatScroll);
});
// 观察“内容容器”尺寸变化（Markdown 渲染/代码高亮/数学公式/行号等都会触发）
let roContent: ResizeObserver | null = null;
onMounted(() => {
  if (contentRef.value) {
    roContent = new ResizeObserver(() => scrollToEnd(false));
    roContent.observe(contentRef.value);
  }
});
onBeforeUnmount(() => {
  roContent?.disconnect();
  roContent = null;
});
// 监听图片加载（子元素 load 冒泡不到父，但在捕获阶段能监听到）
function onImgLoad(){ scrollToEnd(false); }
onMounted(() => {
  chatRef.value?.addEventListener('load', onImgLoad, true); // useCapture = true
});
onBeforeUnmount(() => {
  chatRef.value?.removeEventListener('load', onImgLoad, true);
});

// 医疗对话模式的方法
const triggerFileInput = () => {
  fileInput.value?.click();
};

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    setSelectedImage(file);
  }
};

const handleDrop = (event: DragEvent) => {
  event.preventDefault();
  dragOver.value = false;
  const file = event.dataTransfer?.files[0];
  if (file && file.type.startsWith('image/')) {
    setSelectedImage(file);
  }
};

const setSelectedImage = (file: File) => {
  selectedImage.value = file;
  const reader = new FileReader();
  reader.onload = (e) => {
    imagePreviewUrl.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);
};

const removeImage = () => {
  selectedImage.value = null;
  imagePreviewUrl.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

const startAnalysis = async () => {
  if (!selectedImage.value) return;
  
  analyzing.value = true;
  
  try {
    // 如果是第一次分析（没有输入文本），使用默认的诊断提示
    if (!inputText.value.trim() && chatHistory.value.length === 0) {
      inputText.value = 'AI初步诊断';
    }
    
    // 调用分析API
    const formData = new FormData();
    formData.append('image', selectedImage.value);
    formData.append('input_text', inputText.value);
    formData.append('temperature', temperature.value.toString());
    formData.append('top_p', topP.value.toString());
    
    const response = await fetch(`${API_BASE_URL}/api/medical/analyze-complete`, {
      method: 'POST',
      body: formData
    });
    
    if (response.ok) {
      const result = await response.json();
      
      // 添加用户输入到聊天历史
      if (inputText.value.trim()) {
        chatHistory.value.push({
          role: '用户',
          content: inputText.value,
          timestamp: new Date().toISOString()
        });
      }
      
      // 添加AI回复到聊天历史
      chatHistory.value.push({
        role: 'AI',
        content: result.analysis_result,
        timestamp: new Date().toISOString()
      });
      
      // 清空输入
      inputText.value = '';
      
      // 滚动到底部显示新消息
      scrollToMedicalChatBottom();
      
    } else {
      const errorMsg = '分析失败，请检查网络连接或稍后重试';
      chatHistory.value.push({
        role: '系统',
        content: errorMsg,
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    console.error('分析请求失败:', error);
    chatHistory.value.push({
      role: '系统',
      content: '分析请求失败，请检查网络连接',
      timestamp: new Date().toISOString()
    });
  } finally {
    analyzing.value = false;
  }
};

const clearInput = () => {
  inputText.value = '';
  chatHistory.value = [];
  medicalReport.value = '';
};

const generateReport = async () => {
  if (!chatHistory.value.length) return;
  
  generatingReport.value = true;
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/medical/generate-report`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_history: chatHistory.value,
        patient_info: {
          name: '患者',
          age: '未知',
          gender: '未知',
          history: '无'
        }
      })
    });
    
    if (response.ok) {
      const result = await response.json();
      medicalReport.value = result.report;
    } else {
      alert('报告生成失败');
    }
  } catch (error) {
    console.error('生成报告失败:', error);
    alert('报告生成失败');
  } finally {
    generatingReport.value = false;
  }
};

const downloadReport = () => {
  if (!medicalReport.value) return;
  
  const blob = new Blob([medicalReport.value], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `患者_诊疗报告_${new Date().toISOString().split('T')[0]}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleString('zh-CN');
};

const renderMarkdown = (content: string) => {
  // 简单的markdown渲染，处理基本格式
  return content
    .replace(/## (.*)/g, '<h2>$1</h2>')
    .replace(/### (.*)/g, '<h3>$1</h3>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/- (.*)/g, '<li>$1</li>')
    .replace(/\n/g, '<br>')
    .replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>');
};

// 自动滚动到医疗对话底部
const scrollToMedicalChatBottom = () => {
  nextTick(() => {
    if (medicalChatContainer.value) {
      medicalChatContainer.value.scrollTop = medicalChatContainer.value.scrollHeight;
    }
  });
};

// 监听聊天历史变化，自动滚动到底部
watch(() => chatHistory.value.length, () => {
  scrollToMedicalChatBottom();
});
</script>

<style scoped>
.chat-layout{
  display: grid;
  width: 100%;
  height: 100%;
  min-height: 0;
  grid-template-columns: 220px minmax(0, 1fr);  /* 默认两栏布局 */
  gap: 16px;
  overflow: hidden;  /* 防止溢出 */
}

/* 三栏布局：当显示医疗面板时 */
.chat-layout.with-medical{
  grid-template-columns: 220px minmax(0, 1fr) 280px;  /* 左侧栏 + 中间聊天 + 右侧医疗面板 */
}

/* 左侧栏整体样式 */
.left-column {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 0;
  min-height: 0;
}

/* 左侧上下两部分样式 */
.left-section {
  width: 100%;
  overflow: auto;
  /* 上下各占50%高度 */
  flex: 1 1 50%;
  min-height: 0;
  box-sizing: border-box;
}

/* 模型选择部分 */
.model-selector {
  border-bottom: 1px solid var(--ui-border, #e5e7eb);
  padding-bottom: 8px;
}

/* 会话历史部分 */
.chat-history {
  padding-top: 8px;
}
/* 中间列和右侧列自身不滚动，由内部具体块滚动 */
.middle-column, .right-column{
  min-width: 0;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

/* 左列：模型选择卡片内部滚动，底部贴近 Tag */
.left .card{
  flex: 1 1 auto;
  min-height: 0;
  overflow: auto;
}

/* 中列：历史列表内部滚动 */
.middle .history{
  flex: 1 1 auto;
  min-height: 0;
  overflow: auto;
}

/* 中间列：消息区滚动 + 底部输入固定 */
.middle-column{
  display: grid;
  grid-template-rows: 1fr auto;
  gap: 10px;
  min-height: 0;
}
.middle-column .chat{
  min-height: 0;
  width: 100%;          /* 防止出现"窄盒子" */
  overflow: auto;
}
/* 输入区 */
.input-bar{
  display: grid;
  grid-template-columns: 1fr auto auto;
  gap: 8px;
  align-items: end;
  padding: 8px 12px 12px;
  border-top: 1px solid var(--ui-border, #e5e7eb);
  background: #fff; /* 明确设置为白色，而不是使用变量 */
  z-index: 10; /* 确保输入框在最上层 */
}
.input-bar textarea{
  height: 92px;
  resize: none;
  padding: 10px 12px;
  border: 1px solid var(--ui-border, #e5e7eb);
  border-radius: 10px;
  outline: none;
  background: #fff; /* 明确设置输入框背景为白色 */
  color: #111827; /* 确保文本颜色 */
  font-size: 14px; /* 设置合适的字体大小 */
  line-height: 1.4; /* 设置合适的行高 */
  overflow-y: auto; /* 确保文本超出时可以滚动 */
  min-height: 92px; /* 确保最小高度 */
  max-height: 200px; /* 设置最大高度，防止过高 */
  box-sizing: border-box; /* 确保padding不会影响整体尺寸 */
}
.btn{
  height: 40px;
  padding: 0 14px;
  border-radius: 10px;
  border: 1px solid transparent;
  cursor: pointer;
}
.btn.primary{
  background: #3b82f6;
  color: #fff;
}
.btn.ghost{
  background: #fff;
  border-color: #e5e7eb;
  color: #374151;
}

/* 聊天气泡 */
.msg {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 14px;
  max-width: 100%;
}

/* AI消息：左对齐 */
.msg.assistant {
  justify-content: flex-start;
}

/* 用户消息：右对齐 */
.msg.user {
  justify-content: flex-end;
}

/* 头像样式保持不变，但会根据消息类型自动调整位置 */
.avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #e5e7eb;
  display: grid;
  place-items: center;
  font-size: 12px;
  color: #111827;
  flex-shrink: 0; /* 防止头像被压缩 */
}

/* 用户头像特殊样式 */
.msg.user .avatar {
  background: #dbeafe;
  color: #1e40af;
}

/* 气泡样式调整 */
.bubble {
  max-width: min(720px, 92%);
  padding: 10px 14px;
  border-radius: 14px;
  border: 1px solid var(--bubble-border, #e5e7eb);
  background: var(--bubble-bg, #fff);
  box-shadow: 0 1px 0 rgba(0,0,0,0.02);
}

/* AI气泡：左侧圆角小一点，区分视觉 */
.msg.assistant .bubble {
  --bubble-bg: #f7f9fd;
  --bubble-border: #e6ebf5;
  border-top-left-radius: 6px;
}

/* 用户气泡：右侧圆角小一点 */
.msg.user .bubble {
  --bubble-bg: #eef6ff;
  --bubble-border: #d7e7ff;
  border-top-right-radius: 6px;
}
.scroll-anchor { height: 1px; }

/* 让左右两列内部滚动而非整个页面滚动 */
.left .card,
.middle .history{
  flex: 1 1 auto;
  min-height: 0;
  overflow: auto;
}

/* 适配 */
@media (max-width: 1200px){
  .chat-layout{
    grid-template-columns: minmax(180px, 220px) minmax(0, 1fr);
  }
  
  .chat-layout.with-medical{
    grid-template-columns: minmax(180px, 220px) minmax(0, 1fr) 250px;
  }
}
@media (max-width: 900px){
  .chat-layout{
    grid-template-columns: 1fr;
  }
  
  .chat-layout.with-medical{
    grid-template-columns: 1fr;
  }
  
  .right-column {
    display: none;
  }
}

/* 医疗聊天模式样式 */
.medical-chat {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.medical-chat-header {
  padding: 12px 16px;
  background: var(--primary-light, #eff6ff);
  border-bottom: 1px solid var(--ui-border, #e5e7eb);
}

.medical-chat-header h3 {
  margin: 0;
  font-size: 16px;
  color: var(--primary, #3b82f6);
}

.medical-content {
  flex: 1;
  display: flex;
  min-height: 0;
}

.input-sidebar {
  width: 260px;
  background: var(--secondary-surface, #f9fafb);
  padding: 16px;
  border-right: 1px solid var(--ui-border, #e5e7eb);
  overflow-y: auto;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.image-upload-section h4 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 14px;
  color: var(--foreground, #1f2937);
}

.upload-area {
  border: 2px dashed var(--ui-border, #e5e7eb);
  border-radius: 8px;
  padding: 24px 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #fff;
}

.upload-area.drag-over {
  border-color: var(--primary, #3b82f6);
  background: var(--primary-light, #eff6ff);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.upload-placeholder p {
  margin: 4px 0;
  color: var(--foreground-secondary, #6b7280);
  font-size: 12px;
}

.upload-hint {
  font-size: 11px;
  color: var(--foreground-tertiary, #9ca3af);
}

.image-preview {
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  max-height: 200px;
}

.image-preview img {
  width: 100%;
  height: auto;
  object-fit: contain;
}

.remove-image {
  position: absolute;
  top: 4px;
  right: 4px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
}

.advanced-params {
  margin-top: 20px;
  padding: 12px;
  background: #fff;
  border: 1px solid var(--ui-border, #e5e7eb);
  border-radius: 6px;
}

.advanced-params h5 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 12px;
  color: var(--foreground, #1f2937);
}

.param-row {
  margin-bottom: 8px;
}

.param-row label {
  display: block;
  font-size: 11px;
  color: var(--foreground-secondary, #6b7280);
  margin-bottom: 4px;
}

.slider {
  width: 100%;
  height: 4px;
  border-radius: 2px;
  background: var(--ui-border, #e5e7eb);
  outline: none;
  -webkit-appearance: none;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: var(--primary, #3b82f6);
  cursor: pointer;
}

.analysis-input {
  margin-top: 16px;
}

.analysis-input label {
  display: block;
  font-size: 12px;
  color: var(--foreground-secondary, #6b7280);
  margin-bottom: 4px;
}

.analysis-input textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid var(--ui-border, #e5e7eb);
  border-radius: 4px;
  resize: vertical;
  font-size: 12px;
  line-height: 1.4;
}

.action-buttons {
  margin-top: 16px;
  display: flex;
  gap: 8px;
}

.action-buttons .btn {
  flex: 1;
  height: 36px;
  font-size: 12px;
}

.btn.secondary {
  background: #fff;
  border: 1px solid var(--ui-border, #e5e7eb);
  color: var(--foreground-secondary, #6b7280);
}

.chatbot-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #fff;
}

.no-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--foreground-tertiary, #9ca3af);
}

.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  padding: 8px 12px;
  border-radius: 6px;
  background: var(--secondary-surface, #f9fafb);
  border: 1px solid var(--ui-border, #e5e7eb);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 11px;
}

.message-role {
  font-weight: 600;
  color: var(--primary, #3b82f6);
}

.message-time {
  color: var(--foreground-tertiary, #9ca3af);
}

.message-content {
  font-size: 12px;
  line-height: 1.5;
  color: var(--foreground, #1f2937);
}

.analyzing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  margin-top: 12px;
  background: var(--primary-light, #eff6ff);
  border: 1px solid var(--primary-light-border, #dbeafe);
  border-radius: 4px;
  font-size: 12px;
  color: var(--primary, #3b82f6);
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid var(--ui-border, #e5e7eb);
  border-top: 2px solid var(--primary, #3b82f6);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.report-section {
  padding: 12px 16px;
  border-top: 1px solid var(--ui-border, #e5e7eb);
  background: var(--secondary-surface, #f9fafb);
}

.report-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.report-content {
  padding: 12px;
  border: 1px solid var(--border);
  border-radius: 4px;
  background: var(--background);
}

.markdown-content {
  line-height: 1.5;
  color: var(--foreground);
  font-size: 12px;
}

.markdown-content h2 {
  color: var(--primary);
  border-bottom: 1px solid var(--border);
  padding-bottom: 4px;
  margin: 16px 0 8px 0;
  font-size: 14px;
}

.markdown-content h3 {
  color: var(--foreground);
  margin: 12px 0 6px 0;
  font-size: 13px;
}

.markdown-content ul {
  margin: 8px 0;
  padding-left: 16px;
}

.markdown-content li {
  margin: 4px 0;
}

.markdown-content strong {
  color: var(--primary);
}
</style>